//
//  HDCFMyTradeHistoryVc.m
//  HaoDeCaiFu
//
//  Created by 郑开宏 on 2017/11/2.
//  Copyright © 2017年 郑开宏. All rights reserved.
//

#import "HDCFMyTradeHistoryVc.h"
#import "HDCFTradeHisCell.h"
#import "SVProgressHUD.h"
#import "MJRefresh.h"

#define KTradeHistory @"/public/transaction/get-order-list"

@interface HDCFMyTradeHistoryVc ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSDictionary *typeDict;

@property (nonatomic, weak) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *historyArray;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) NSInteger pageTwo;

@property (nonatomic, strong) NSMutableArray *btnArray;

@property (nonatomic, strong) NSMutableArray *historyArrayTwo;

@property (nonatomic, assign) BOOL isFirst;



@end

@implementation HDCFMyTradeHistoryVc

- (NSMutableArray *)historyArrayTwo{
    if (!_historyArrayTwo) {
        self.historyArrayTwo = [NSMutableArray array];
    }
    return _historyArrayTwo;
}

- (NSMutableArray *)btnArray{
    if (!_btnArray) {
        self.btnArray = [NSMutableArray array];
    }
    return _btnArray;
}

- (NSMutableArray *)historyArray{
    if (!_historyArray) {
        self.historyArray = [NSMutableArray array];
    }
    return _historyArray;
}

- (NSDictionary *)typeDict{
    if (!_typeDict) {
        self.typeDict = @{@"buy":@"申购",
                          @"ipo":@"认购",
                          @"sell":@"赎回",
                          @"rsp":@"定投",
                          @"dividend":@"红利再投",
                          @"intra.swtich":@"同公司转换",
                          @"inter.switch":@"跨公司转换",
                          @"rapid.sell":@"快速取现",
                          @"sell.force":@"强制赎回",
                          @"units.increment":@"份额强增",
                          @"units.decrement":@"份额强减"
                          };
    }
    return _typeDict;
}

- (void)topBtnClick:(UIButton *)btn{
    for (int i = 0; i < 2; i++) {
        UIButton *btn = _btnArray[i];
        [btn setTitleColor:ZKcolor(30, 30, 30) forState:UIControlStateNormal];
    }
    [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    if (btn.tag == 0) {
        if (self.isFirst == YES) {
            return;
        }else{
            self.isFirst = YES;
            [self.tableView reloadData];
        }
        
    }else{
        if (self.isFirst == NO) {
            return;
        }else{
            self.isFirst = NO;
            [self.tableView reloadData];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isFirst = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    self.page = 1;
    self.pageTwo = 1;
    for (int i = 0; i < 2; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:15]];
        btn.frame = CGRectMake((screenWidth / 2 + 1) * i, KNavHeight, screenWidth / 2, 44);
        btn.tag = i;
        if (i == 0) {
            [btn setTitle:@"基金和理财" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            
        }else{
            [btn setTitle:@"组合" forState:UIControlStateNormal];
            [btn setTitleColor:ZKcolor(33, 33, 33) forState:UIControlStateNormal];
        }
        [self.btnArray addObject:btn];
        [self.view addSubview:btn];
        [btn addTarget:self action:@selector(topBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIView *viewOne =[[UIView alloc] initWithFrame:CGRectMake(screenWidth / 2, KNavHeight, 1, 44)];
    viewOne.backgroundColor = ZKcolor(245, 245, 245);
    [self.view addSubview:viewOne];
    
    
    UIView *slider = [[UIView alloc] initWithFrame:CGRectMake(0, KNavHeight + 44, screenWidth, 1)];
    slider.backgroundColor = ZKcolor(245, 245, 245);
    [self.view addSubview:slider];
    
    CGRect rect = CGRectMake(0, KNavHeight + 44 + 2, screenWidth, screenHeight - 44 - KNavHeight);
    UITableView *tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView.separatorColor = ZKcolor(245, 245, 245);
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.navigationItem setTitle:@"交易记录"];
    [self getMyTradeHistory];
    [self getMyTradeHistoryZuHe];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(mainRefresh)];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(mainLoadMore)];
    
}

- (void)mainRefresh{
    self.page = 1;
    self.pageTwo = 1;
    if (_isFirst == YES) {
       [self.historyArray removeAllObjects];
        [self getMyTradeHistoryNOhud];
    }else{
        [self.historyArrayTwo removeAllObjects];
        [self getMyTradeHistoryZuHeNoHud];
    }
    
    
}

- (void)mainLoadMore{
    if (_isFirst == YES) {
        self.page++;
        [self getMyTradeHistoryNOhud];
    }else{
        self.pageTwo++;
        [self getMyTradeHistoryZuHeNoHud];
    }
}

- (NSString *)dictionaryToJson:(NSDictionary *)dic{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

- (void)getMyTradeHistory{
    [SVProgressHUD show];
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.page];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KTradeHistory};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925279"
//        [12]    (null)    @"transactionType" : @"buy"
//        [12]    (null)    @"transactionType" : @"sell"
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925278"
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925287"
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925286"
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925292"
//        [10]    (null)    @"merchantNumber" : @"ZHD2017112925294"
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dict = result[@"data"];
            [self.historyArray addObjectsFromArray:dict[@"data"]];
            NSArray *array = dict[@"data"];
            if (array.count == 10) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
            
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
    }];
    
}

- (void)getMyTradeHistoryZuHe{
    [SVProgressHUD show];
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.pageTwo];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/product/portfolio/get-portfolio-order-list"};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSString *code = result[@"code"];
//[9]    (null)    @"merchantNumber" : @"ZHD2017112802497"
//        [10]    (null)    @"transactionType" : @"buy"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925273"
//        [10]    (null)    @"transactionType" : @"sell"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925277"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925280"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925277"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925274"
//        [9]    (null)    @"merchantNumber" : @"ZHD2017112925293"
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dict = result[@"data"];
            [self.historyArrayTwo addObjectsFromArray:dict[@"data"]];
            NSArray *array = dict[@"data"];
            if (array.count == 10) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
    
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
    }];
    
}
- (void)getMyTradeHistoryZuHeNoHud{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.pageTwo];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:@"/public/product/portfolio/get-portfolio-order-list"};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            NSDictionary *dict = result[@"data"];
            [self.historyArrayTwo addObjectsFromArray:dict[@"data"]];
            NSArray *array = dict[@"data"];
            if (array.count == 10) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView.mj_header endRefreshing];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        
    }];
    
}

- (void)getMyTradeHistoryNOhud{
    NSMutableDictionary *paramets = [NSMutableDictionary dictionary];
    paramets[@"accountNumber"] = kAcount;
    paramets[@"pageSize"] = @"10";
    paramets[@"pageIndex"] = [NSString stringWithFormat:@"%ld", self.page];
    NSString *jsonStr = [self dictionaryToJson:paramets];
    NSDictionary *paramet = @{KparametOne:jsonStr,
                              KparametTwo:KTradeHistory};
    [HttpRequest sendGetRequestWithURL:nil WithParamets:paramet success:^(id result) {
        
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"0000"]) {
            [SVProgressHUD dismiss];
            NSDictionary *dict = result[@"data"];
            [self.historyArray addObjectsFromArray:dict[@"data"]];
            NSArray *array = dict[@"data"];
            if (array.count == 10) {
                [self.tableView.mj_footer endRefreshing];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [self.tableView reloadData];
        }else{
            [SVProgressHUD showInfoWithStatus:result[@"message"]];
            [SVProgressHUD dismissWithDelay:1.0];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } failure:^(NSError *errer) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [SVProgressHUD dismissWithDelay:1.0];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (_isFirst == YES) {
        return self.historyArray.count;
    }else{
       return self.historyArrayTwo.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"cellID";
    HDCFTradeHisCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [HDCFTradeHisCell HDCFTradeHisCell];
    }
    
    if (_isFirst == YES) {
        NSDictionary *dict = self.historyArray[indexPath.row];
        cell.dataDict = dict;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }else{
        NSDictionary *dict = self.historyArrayTwo[indexPath.row];
        cell.dataDictTwo = dict;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 85;
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
